package com.young.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.young.dao.ClubDao;
import com.young.entity.Club;
import com.young.service.ClubService;
import com.young.tool.PageData;
import com.young.tool.UploadImgTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 描述:
 *
 * @author BluceYoung
 * @create 2020-12-11 11:52
 * B站：TeacherYoung凌风
 * www.teacheryoung.com
 */
@Service
public class ClubServiceImpl implements ClubService {

    @Autowired
    ClubDao clubDao;

    /**
     * 新增或修改社团信息
     *
     * @param club
     * @return
     */
    @Override
    public boolean save(Club club) {
        if(club.getId()!=null){//修改
            club.setUpdateTime(new Date());
            clubDao.update(club);
        }else{//新增
            club.setStatus(1);
            clubDao.insert(club);
        }
        return false;
    }

    /**
     * 创建新社团
     *
     * @param club     新社团信息
     * @param savePath logo保存路径
     * @param imgData  logo数据
     * @return
     */
    @Override
    public boolean createNewClub(Club club, String savePath, String imgData) throws Exception {
        Club condition=new Club();
        condition.setUserId(club.getUserId());
        Club result = clubDao.get(condition);
        if(result!=null){
            throw new Exception("已经创建过社团");
        }
        this.save(club);//新增社团
        UploadImgTool.generateImg(imgData,savePath,club.getId()+".jpg");
        //设置logo图片的访问路径，加时间戳
        String logoName=club.getId()+".jpg?r="+(new Date()).getTime();
        club.setLogo(logoName);
        this.save(club);//修改社团logo
        return true;
    }

    /**
     * 查询一条社团信息
     *
     * @param condition 条件
     * @return
     */
    @Override
    public Club get(Club condition) {

        return clubDao.get(condition);
    }

    /**
     * 分页查询社团数据
     *
     * @param condition 查询条件
     * @param pageNum   页码
     * @param pageSize  每页条数
     * @param sortName  排序列
     * @param sortOrder 排序类型 asc/desc
     * @return
     */
    @Override
    public PageData<Club> listClubs(Club condition, Integer pageNum, Integer pageSize, String sortName, String sortOrder) {
        PageData<Club> pageData=new PageData<>();
        Page<Club> page= PageHelper.startPage(pageNum,pageSize);
        List<Club> list = clubDao.listClubs(condition, sortName, sortOrder);
        pageData.setRows(list);
        pageData.setTotal((int)page.getTotal());
        return pageData;
    }
}
